<?php
/**
 * IndexController.class.class.php
 * 
 * @author tommy <streen003@gmail.com>
 * @copyright  Copyright (c) 2010 Tommy Software Studio.
 * @link http://www.doitphp.com
 * @package tools
 */
class IndexController extends Controller {
	
	/**
	 * 正则表达式
	 */
	public function indexAction() {
		
		//parse login state
		$this->parse_login();
		
		//assign params
		$this->assign(array(
		'title'		=> '正则表达式测试工具',		
		));
		
		//display page
		$this->display();
	}
	
	/**
	 * ajax处理正则表达式
	 */
	public function ajax_handle_regexpAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$regexp_mode 	= trim($_POST['regexp_mode']);
		$is_s_state		= $this->post('is_s_state');
		$is_i_state		= $this->post('is_i_state');
		$regexp_content	= trim($_POST['regexp_content']);
		
		//parse params
		if (empty($regexp_mode) || empty($regexp_content)) {
			exit();
		}
		
		$extension_mode = ''; 
		if ($is_i_state == 'true') {
			$extension_mode .= 'i'; 
		}
		if ($is_s_state == 'true') {
			$extension_mode .= 's';
		}
		
		$regexp_mode = str_replace('\\\\', '\\', $regexp_mode);
		$regexp_mode = '#' . $regexp_mode . '#' . $extension_mode;
		
		if (preg_match_all($regexp_mode, $regexp_content, $output)) {
			echo '<span style="color:#D54E21;">匹配成功!</span><br/>';
			echo '匹配模式为: <span style="color:#2583AD;">', $regexp_mode, '</span><br/>';
			echo '匹配的字符为: ', htmlspecialchars($output[0][0]);
		} else {
			echo '<span style="color:#D54E21;">匹配失败!</span><br/>';
			echo '匹配模式为: <span style="color:#2583AD;">', $regexp_mode, '</span>';
		}
	}

	/**
	 * Controller管理
	 */
	public function controllerAction() {
		
		//parse login state
		$this->parse_login();
		
		//assign params
		$this->assign(array(
		'title'		=> 'Controller管理',
		));
		
		//display page
		$this->display();
	}
	
	/**
	 * AJAX创建controller文件
	 */
	public function ajax_create_controllerAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$controller_name 		= $this->post('controller_name');
		$controller_view_state 	= $this->post('controller_view_state');
		
		//parse controller name
		if (!$controller_name) {
			exit();
		}
		
		$this->parse_webapp_root();
		
		$controller_name 		= ucfirst(strtolower($controller_name)) . 'Controller';		
		$controller_file_dir 	= WEBAPP_ROOT . 'application/controllers';
		$controller_file		= $controller_file_dir . '/' . $controller_name . '.class.php';
		
		//parse controller dir
		if (!is_dir($controller_file_dir)) {
			mkdir($controller_file_dir, 0777);
		}
		
		//分析所要创建的controller文件是否 存在
		if (file_exists($controller_file)) {
			echo '所要创建的文件已经存在!';
		} else {
			$file_content 	= "<?php\r\nclass ".$controller_name." extends Controller {\r\n\r\n\tpublic function indexAction() {\r\n\r\n\t}\r\n}";
			$result 		= file_put_contents($controller_file, $file_content, LOCK_EX);
			
			//创建视图目录
			if ($controller_view_state == 'true') {
				$view_dir = WEBAPP_ROOT . 'application/views/' . strtolower(substr($controller_name, 0, -10));
				if (!is_dir($view_dir)) {
					mkdir($view_dir, 0777);
				}
			}
			
			echo ($result == true) ? $controller_name . '文件创建成功!' : '对不起,' . $controller_name . '文件创建失败!';
		}
	}
	
	/**
	 * AJAX创建widget
	 */
	public function ajax_create_widgetAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$widget_name		= $this->post('widget_name');		
		
		//parse widget name
		if (!$widget_name) {
			exit();
		}
		
		$this->parse_webapp_root();
		
		$widget_name 	= strtolower($widget_name);
				
		$widget_dir 	= WEBAPP_ROOT . 'application/widgets';
		if (!is_dir($widget_dir)) {
			mkdir($widget_dir, 0777);
		}
		
		$widget_file	= $widget_dir . '/' . ucfirst($widget_name) . 'Widget.class.php';
		if (file_exists($widget_file)) {
			echo '所要创建的widget文件已存在!';
		} else {
			$file_content 	= "<?php\r\nclass ".$widget_name."Widget extends Widget {\r\n\r\n\tpublic function render(){\r\n\r\n\t}\r\n}";	
			$result 		= file_put_contents($widget_file, $file_content, LOCK_EX);
			
			echo ($result == true) ? $widget_name . '的widget文件创建成功!' : $widget_name . '的widget文件创建失败!';
		}
	}
	
	/**
	 * AJAX创建module
	 */
	public function ajax_create_moduleAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$module_name		= strtolower($this->post('module_name'));
		$module_view_state	= $this->post('module_view_state');
		if (!$module_name) {
			exit();
		}

		$this->parse_webapp_root();
		
		//创建模块目录(modules).
		if (!is_dir(WEBAPP_ROOT . 'modules')) {
			mkdir(WEBAPP_ROOT . 'modules', 0777);
		}
		
		$module_dir = WEBAPP_ROOT . 'modules/' . $module_name;
		if (!is_dir($module_dir)) {
			mkdir($module_dir, 0777);
		}
		
		$module_name = ucfirst($module_name);
		$module_file	= $module_dir . '/' . $module_name . 'Module.class.php';
		
		//创建视图目录
		if ($module_view_state == 'true' && !is_dir($module_dir . '/views')) {
			mkdir($module_dir . '/views', 0777);
		}
		
		if (file_exists($module_file)) {
			echo '所要创建的', $module_name , ' module文件已存在!';
			exit();
		}
		
		$module_content	= "<?php\r\nif (!defined('IN_DOIT')) { exit(); }\r\n\r\nclass " . $module_name . "Module extends Module {\r\n\r\n\tpublic function __construct() {\r\n\r\n\t}\r\n}";
		
		if (file_put_contents($module_file, $module_content, LOCK_EX)) {						
			echo $module_name, ' Module文件创建成功!';
		} else {
			echo $module_name, ' Module文件创建失败!';
		}
	}
	
	/**
	 * Modle管理
	 */
	public function modelAction() {
		
		//parse login state
		$this->parse_login();
		
		//assign params
		$this->assign(array(
		'title'		=> 'Modle管理',
		));
		
		//display page
		$this->display();
	}
	
	/**
	 * AJAX创建modle文件
	 */
	public function ajax_create_modelAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$model_name		= strtolower($this->post('model_name'));
		$fields_state	= $this->post('fields_state');
		
		//parse params
		if (!$model_name) {
			exit();
		}
		
		$this->parse_webapp_root();
		
		$model_dir 	= WEBAPP_ROOT . 'application/models';
		$model_name	= ucfirst($model_name);
		
		$model_file	= $model_dir . '/' . $model_name . 'Model.class.php';
		
		//parse models dir
		if (!is_dir($model_dir)) {
			mkdir($model_dir, 0777);
		}
		
		//parse modle file.
		if (file_exists($model_file)) {
			echo $model_name, '的modle文件已存在!';
		} else {
			//分析modle文件的内容
			if ($fields_state == 'true') {
				//连接数据库				
				$config_file = WEBAPP_ROOT . 'application/config/config.ini.php';
		
				if (!is_file($config_file)) {
					echo '连接数据库配置文件不存在,请先创建config文件!';
					exit();
				}
				//加载数据库配置文件.
				$params = include $config_file;
		
				//分析,检测配置文件内容
				if (!is_array($params)) {
					echo 'Config配置文件内容错误!';
					exit();
				}		
		
				//进行trim()数据处理
				$params['driver']	= trim($params['driver']);
				if ($params['driver'] == 'mysqli' || $params['driver'] == 'mysql' || $params['driver'] == 'pdo_mysql') {
					$params['host'] 	= trim($params['host']);
					$params['username'] = trim($params['username']);
					$params['password'] = trim($params['password']);
					$params['dbname'] 	= trim($params['dbname']);
					
					//参数默认，编码默认utf8
					$params['charset'] = ($params['charset']) ? trim($params['charset']) : 'utf8';
					
					//获取数据表前缀，默认为空
					$this->prefix = ($params['prefix']) ? trim($params['prefix']) : '';
					
					//实例化$db（数据库连接）
					switch ($params['driver']) {
						case 'mysql':
							$db = db_mysql::getInstance($params);
							break;
						case 'pdo_mysql':
							//分析dsn信息
							if (!$params['dsn']) {
								$dsn_array 			= array();
								$dsn_array['host']	=$params['host'];
								$dsn_array['dbname']=$params['dbname'];
		
								if (!empty($params['port'])){
									$dsn_array['port']=$params['port'];
								}
								$params['dsn'] = sprintf('%s:%s', 'mysql', http_build_query($dsn_array, '', ';'));
							}
							$db = db_pdo::getInstance($params);				
							break;
						default:
							$db = db_mysqli::getInstance($params);	
					}
					
					//将数据库的用户名及密码及时从内存中注销，提高程序安全性
					unset($params['username']);
					unset($params['password']);
					
					$model_name	= strtolower($model_name);
					
					$table_info	= $db->get_array("SHOW FIELDS FROM `{$model_name}`");
					
					$fields 		= array();
					$primary_key 	= array();
					foreach ($table_info as $lines) {
						//获取主键信息		
						if ($lines['Key'] == 'PRI') {
							$primary_key[] = $lines['Field'];				
						}
					
						//获取字段信息
						$fields[] = $lines['Field'];
					}
				} else {
					$primary_key 	= '';
					$fields			= array();
				}
				
				//分析model文件内容
				$file_content 	= "<?php\r\nclass " . $model_name . "Model extends Model {\r\n\r\n";
				$file_content  .= "\tprotected function get_primary_key() {\r\n\t\treturn \$this->primary_key = '{$primary_key[0]}';\r\n\t}\r\n\r\n\tprotected function get_table_fields() {\r\n\t\treturn \$this->table_field = " . var_export($fields, true) . ";\r\n\t}\r\n}";
			} else {
				$file_content = "<?php\nclass " . $model_name . "Model extends Model {\n\n}";
			}

			if (file_put_contents($model_file, $file_content, LOCK_EX)) {
				echo $model_name, '的modle文件创建成功!';
			} else {
				echo $model_name, '的modle文件创建失败!';
			}
		}
	}
	
	/**
	 * 创建全部的model文件
	 */
	public function ajax_create_all_modelAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$fields_state = $this->post('fields_state');
		
		$this->parse_webapp_root();
		
		//分析model文件目录
		$model_dir 	= WEBAPP_ROOT . 'application/models';
		
		if (!is_dir($model_dir)) {
			mkdir($model_dir, 0777);
		}
		
		//连接数据库				
		$config_file = WEBAPP_ROOT . 'application/config/config.ini.php';
		
		if (!is_file($config_file)) {
			echo '连接数据库配置文件不存在,请先创建config文件!';
			exit();
		}
		//加载数据库配置文件.
		$params = include $config_file;
		
		//分析,检测配置文件内容
		if (!is_array($params)) {
			echo 'Config配置文件内容错误!';
			exit();
		}		
		
		//进行trim()数据处理
		$params['driver']	= trim($params['driver']);
		if ($params['driver'] == 'mysqli' || $params['driver'] == 'mysql' || $params['driver'] == 'pdo_mysql') {
			$params['host'] 	= trim($params['host']);
			$params['username'] = trim($params['username']);
			$params['password'] = trim($params['password']);
			$params['dbname'] 	= trim($params['dbname']);
			
			//参数默认，编码默认utf8
			$params['charset'] = ($params['charset']) ? trim($params['charset']) : 'utf8';
					
			//获取数据表前缀，默认为空
			$params['prefix'] = ($params['prefix']) ? trim($params['prefix']) : '';
			
			//实例化$db（数据库连接）
			switch ($params['driver']) {
				case 'mysql':
					$db = db_mysql::getInstance($params);
					break;
				case 'pdo_mysql':
					//分析dsn信息
					if (!$params['dsn']) {
						$dsn_array 			= array();
						$dsn_array['host']	=$params['host'];
						$dsn_array['dbname']=$params['dbname'];
		
						if (!empty($params['port'])){
							$dsn_array['port']=$params['port'];
						}
						$params['dsn'] = sprintf('%s:%s', 'mysql', http_build_query($dsn_array, '', ';'));
					}
					$db = db_pdo::getInstance($params);				
					break;
				default:
					$db = db_mysqli::getInstance($params);	
			}
			
			//将数据库的用户名及密码及时从内存中注销，提高程序安全性
			unset($params['username']);
			unset($params['password']);
			
			//获取数据库中的数据表
			$table_list_array = $db->get_array("SHOW TABLES");
			
			foreach($table_list_array as $lines) {				
				$table_name = preg_replace('/^'. $params['prefix'] . '/', '', $lines['Tables_in_' . $params['dbname']]);
				$table_name = ucfirst(strtolower($table_name));				
				
				$model_file = $model_dir . '/' . $table_name . 'Model.class.php';
				
				//当model文件不存在时
				if (!file_exists($model_file)) {
					//是否有字段信息
					if ($fields_state == 'true') {
						//获取数据表字段信息
						$table_name_tmp 	= strtolower($table_name);
						$table_info			= $db->get_array("SHOW FIELDS FROM `{$table_name_tmp}`");
						
						$fields 		= array();
						$primary_key	= array();
						foreach ($table_info as $lines) {
							//获取主键信息		
							if ($lines['Key'] == 'PRI') {
								$primary_key[] = $lines['Field'];				
							}
					
							//获取字段信息
							$fields[] = $lines['Field'];
						}
						
						//分析model文件内容
						$file_content 	= "<?php\r\nclass " . $table_name . "Model extends Model {\r\n\r\n";
						$file_content  .= "\tprotected function get_primary_key() {\r\n\t\treturn \$this->primary_key = '{$primary_key[0]}';\r\n\t}\r\n\r\n\tprotected function get_table_fields() {\r\n\t\treturn \$this->table_field = " . var_export($fields, true) . ";\r\n\t}\r\n}";
					} else {
						$file_content = "<?php\nclass " . $table_name . "Model extends Model {\n\n}";
					}
					
					if (!file_put_contents($model_file, $file_content, LOCK_EX)) {
						echo $table_name, '的Model文创建失败!';
						break;
					}
				}
			}
			echo '全部Model文件已创建完成!';			
		} else {
			echo '生成全部的model文件目前只支持mysql数据库!';
		}		
	}
	
	/**
	 * AJAX清空一个model文件的缓存
	 */
	public function ajax_clear_modelAction() {
		
		//parse login state
		$this->parse_login(true);
		
		$this->parse_webapp_root();
		
		//get params
		$model_cache_name = strtolower($this->post('model_cache_name'));
		if (!$model_cache_name) {
			exit();
		}
		
		$model_cache_file = WEBAPP_ROOT . 'cache/models/' . $model_cache_name . '_model.data.php';
		
		if (file_exists($model_cache_file)) {
			unlink($model_cache_file);
		}
		
		echo $model_cache_name, ' Model缓存文件已删除!';
	}
	
	/**
	 * AJAX删除全部的model缓存
	 */
	public function ajax_clear_all_modelAction() {
		
		//parse login state
		$this->parse_login(true);
		
		$this->parse_webapp_root();
		
		$model_cache_dir 	= WEBAPP_ROOT . 'cache/models';		
		$cache_dir_content 	= opendir($model_cache_dir);
		
		while(false !== ($file = readdir($cache_dir_content))){
				
			if($file == '.' || $file == '..' || $file == 'index.html' || $file == '.svn' || $file == '.cvs'){
				continue;
			}
				
			unlink($model_cache_dir . '/' . $file);
		}
		
		echo 'Model缓存文件全部清除完毕!';
	}
	
	/**
	 * Webapp管理
	 */
	public function webappAction() {
		
		//parse login state
		$this->parse_login();
		
		//assign params
		$this->assign(array(
		'title'		=> 'WebApp管理',
		));
		
		//display page
		$this->display();
	}
	
	/**
	 * AJAX生成config文件
	 */
	public function ajax_create_configAction() {
		
		//parse login state
		$this->parse_login(true);
		
		$this->parse_webapp_root();
		
		//get params
		$config_array['driver']		= $this->post('driver_name');
		$config_array['host']		= $this->post('server_name');
		$config_array['username']	= $this->post('user_name');
		$config_array['password']	= $this->post('password');
		$config_array['dbname']		= $this->post('database_name');
		
		$config_array['charset']	= $this->post('database_encode');
		$config_array['prefix']		= $this->post('database_prefix');
		
		if (!$config_array['driver']) {
			exit();
		}
		
		switch ($config_array['driver']) {
			case 'mysqli':
			case 'mysql':
			case 'pdo_mysql':				
				$config_array['charset']	= empty($config_array['charset']) ? 'utf8' : str_replace(array('utf-8', 'UTF-8'), 'utf8', $config_array['charset']);
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				}
				$config_array['port']		= 3306;
				break;
				
			case 'postgresql':
			case 'pdo_postgresql':
				$config_array['port']	= 5432;
				if (empty($config_array['charset'])) {
					unset($config_array['charset']);
				}
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 				
				break;
				
			case 'sqlite2':				
			case 'sqlite3':
				if (empty($config_array['dbname'])) {
					unset($config_array['dbname']);
				}
				if (empty($config_array['charset'])) {
					unset($config_array['charset']);
				}
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 		
				break;
				
			case 'oracle':
			case 'pdo_oracle':	
				$config_array['port']	= 1521;
				$config_array['charset']	= empty($config_array['charset']) ? 'utf8' : $config_array['charset'];
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 	
				break;
				
			case 'mssql':
				if (empty($config_array['charset'])) {
					unset($config_array['charset']);
				}
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 		
				break;
				
			case 'pdo':
				$config_array['dsn']	= $config_array['host'];
				unset($config_array['host']);
				
				if (empty($config_array['charset'])) {
					unset($config_array['charset']);
				}
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 		
				break;
				
			case 'mongodb':
				$config_array['port']	= 27017;
				if (empty($config_array['charset'])) {
					unset($config_array['charset']);
				}
				if (empty($config_array['prefix'])) {
					unset($config_array['prefix']);
				} 				
				break;				
		}
		
		//parse config file
		$config_dir	 = WEBAPP_ROOT . 'application/config';
		$config_file = $config_dir . '/config.ini.php';
		if (file_exists($config_file)) {
			echo 'Config配置文件已存在!';
			exit();
		}
		
		if (!is_dir($config_dir)) {
			mkdir($config_dir, 0777);
		}
		
		$file_content = "<?php\r\nif (!defined('IN_DOIT')) exit();\r\nreturn " . var_export($config_array, true).";";
		
		if (file_put_contents($config_file, $file_content, LOCK_EX)) {
			echo 'Config配置文件创建成功!';
		} else {
			echo 'Config配置文件创建失败!';
		}
	}
	
	/**
	 * AJAX生成项目目录(app dir)
	 */
	public function ajax_create_app_dirAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$module_state	= $this->post('module_state');
		$rewrite_state	= $this->post('rewrite_state');
		$theme_state	= $this->post('theme_state');
		$webserver_name	= $this->post('webserver_name');
		
		$app_root		= substr(WEBAPP_ROOT, 0, -1);
		if (!is_dir($app_root)) {			
			echo '对不起,项目(WebApp)根目录:', $app_root, '不存在!请创建项目根目录';
			exit();
		}
			
		$app_dir_array	= array(
		'application',
		'application/config',
		'application/controllers',
		'application/models',
		'application/views',
		'application/widgets',
		'application/extensions',
		'application/views/error',
		'application/views/layout',
		'application/widgets/views',	
		
		'assets',
		'assets/doit',
		'assets/images',
		'assets/js',
		'assets/doit/images',
		'assets/doit/js',
		
		'cache',
		'cache/data',
		'cache/models',
		'cache/temp',
		'cache/views',
		'cache/views/widgets',		
		'logs',
		);
		
		if ($module_state == 'true') {
			$app_dir_array[] = 'modules';
		}
		if ($theme_state == 'true') {
			$app_dir_array[] = 'themes';
			$app_dir_array[] = 'themes/default';
		}
		
		//生成目录
		foreach ($app_dir_array as $lines) {
			$app_dir_name	= $app_root . '/' . $lines;
			if (!is_dir($app_dir_name)) {
				mkdir($app_dir_name, 0777);
			}
		}
		
		//doit仓库中js文件及图片的迁移
		$file_list = $this->instance('file_list');
				
		$file_list->copy_dir(DOIT_ROOT . 'vendors', $app_root . '/assets/doit/js');
		$file_list->copy_dir(DOIT_ROOT . 'views/images', $app_root . '/assets/doit/images');
		
		//生成目录权限控制文件
		if ($webserver_name == 'apache') {
			$deny_dir_array = array(
			'application',
			'cache',
			'logs',			
			);
			
			foreach ($deny_dir_array as $lines) {
				$htaccess_file = $app_root . '/' . $lines . '/.htaccess';
				if (!is_file($htaccess_file)) {
					file_put_contents($htaccess_file, 'deny from all', LOCK_EX);
				}
			}
			
			$file_403_content = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>Directory access is forbidden.</p></body></html>';
			
			$asset_403_array  = array('assets', 'assets/doit');
			if ($module_state == 'true') {
				$asset_403_array[] = 'modules';
			}
			
			foreach ($asset_403_array as $lines) {
				$file_403_index = $app_root . '/' . $lines . '/index.html';
				if (!is_dir($file_403_index)) {
					file_put_contents($file_403_index, $file_403_content, LOCK_EX);
				}
			}
		} else {
			$file_403_content = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>Directory access is forbidden.</p></body></html>';
			
			foreach ($app_dir_array as $lines) {
				$file_403_index = $app_root . '/' . $lines . '/index.html';
				if (!is_dir($file_403_index)) {
					file_put_contents($file_403_index, $file_403_content, LOCK_EX);
				}
			}
		}
		
		//生成项目首页index.php
		if (!is_file($app_root . '/index.php')) {
			$app_index_content = <<<EOT
<?php
/**
 * index.php
 * 
 * @author tommy <streen003@gmail.com>
 * @copyright  Copyright (c) 2010 Tommy Software Studio.
 * @link http://www.doitphp.com
 * @package application system
 */

define('IN_DOIT', true);

//define('DOIT_DEBUG', true);
//define('DOIT_REWRITE', true);

//define('URL_SUFFIX', '.html');
//define('URL_SEGEMENTATION', '/');
//define('CUSTOM_URL_ROUTER', true);

/**
 * 定义项目所在路径即:APP_ROOT
 */
define('APP_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);

/**
 * 加载DoitPHP框架的初始化文件,如果必要可以修改文件路径
 */
require_once APP_ROOT.'doitphp/doit.class.php';

/**
 * 启动网站进程
 */
doit::run();			
EOT;
			file_put_contents($app_root . '/index.php', $app_index_content, LOCK_EX);			
		}
		
		//生成路由重定向的.htaccess文件
		if ($rewrite_state == 'true' && ($webserver_name == 'apache') && !is_file($app_root . '/.htaccess')) {
			$file_htaccess_content =<<<EOT
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]			
EOT;
			file_put_contents($app_root . '/.htaccess', $file_htaccess_content, LOCK_EX);
		}
		
		//生成项目爬虫引导文件
		if (!is_file($app_root . '/robots.txt')) {
			$file_robots_content =<<<EOT
User-agent: *
Crawl-delay: 10
Disallow: /doitphp/
Disallow: /tools/
Disallow: /application/
Disallow: /assets/
Disallow: /cache/
Disallow: /themes/
Disallow: /logs/			
EOT;
			file_put_contents($app_root . '/robots.txt', $file_robots_content, LOCK_EX);
		}
						
		echo 'WebApp项目目录创建成功!';
	}
	
	/**
	 * AJAX检查项目目录的读写权限
	 */
	public function ajax_check_app_dirAction() {
		
		//parse login state
		$this->parse_login(true);
		
		$app_root		= substr(WEBAPP_ROOT, 0, -1);
		
		if (!is_dir($app_root)) {
			echo '对不起!没有发现所要检测的项目(WebApp)根目录:', $app_root;
			exit();
		}
		
		if (!is_writable($app_root)) {
			echo '当前项目目录无法写入!';
			exit();
		}
		
		//app目录列表
		$app_dir_array	= array(		
		'application/config',
		'application/controllers',
		'application/models',
		'application/views',
		'application/widgets',		
		'application/extensions/modules',
		'cache/data',
		'cache/models',
		'cache/temp',
		'cache/views',
		'cache/views/widgets',		
		'logs',
		);
		
		$show_message = array();
		foreach ($app_dir_array as $line) {
			$dir_name = $app_root . '/' . $line;
			if (is_dir($dir_name) && !is_writable($dir_name)) {
				$show_message[] = $line;
			}
		}
		
		if (empty($show_message)) {
			echo '恭喜!当前WebApp目录权限检测通过!';
		} else {
			echo '对不起!当前WebApp目录权限未能检测通过!没有写入权限的目录为:', implode(', ', $show_message);
		}
	}
	
	/**
	 * AJAX检测PHP的系统环境是否适于运行本框架
	 */
	public function ajax_check_system_infoAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//php version
		if (!version_compare(PHP_VERSION,"5.1.0",">=")) {
			echo '对不起,当前的PHP版本应该等于或高于5.1!';
			exit();
		}
		
		//$_SERVER变量 
		$vars=array('HTTP_HOST','SERVER_NAME','SERVER_PORT','SCRIPT_NAME','SCRIPT_FILENAME','PHP_SELF','HTTP_ACCEPT','HTTP_USER_AGENT');
		$missing=array();
		foreach ($vars as $var) {
			if(!isset($_SERVER[$var])) {
				$missing[]=$var;
			}				
	    }
	    if (!empty($missing)) {
	    	echo '对不起!$_SERVER 没有:', implode(', ', $missing), ' 运行doitPHP所必须的参数!';
	    	exit(); 
	    }
		
		//SPL扩展
		if (!extension_loaded("SPL")) {
			echo '对不起,当前PHP的配置不支持SPL扩展!这是运行doitPHP必须支持的!';
			exit();
		}
		
		//正则表达式
		if (!extension_loaded("pcre")) {
			echo '对不起,当前PHP的配置不支持PCRE扩展,无法处理正则表达式!';
			exit();
		}
		
		//GD库
		if (!extension_loaded('gd')) {
			echo '对不起,当前的PHP配置不支持GD库扩展,无法运行图片处理等操作!';
			exit();
		}
		
		echo '恭喜!,当前的PHP配置环境可以运行doitPHP核心程序!';
	}
	
	/**
	 * 其它工具
	 */
	public function otherAction() {
		
		//parse login state
		$this->parse_login();
		
		//assign params
		$this->assign(array(
		'title'		=> '其它工具',
		));
		
		//display page
		$this->display();
	}
	
	/**
	 * AJAX计算字符长度
	 */
	public function ajax_count_strlenAction() {
		
		//parse login state
		$this->parse_login(true);
		
		//get params
		$str_content = trim($_POST['str_content']);
		if (!$str_content) {
			exit();
		}
		
		//handle strlen
		echo '字符串长度:', strlen($str_content);
	}
	
	/**
	 * 分析用户是否登陆
	 */
	public function parse_login($item = false) {
		
		$login_state = cookie::get('doit_tools_login_state');
		
		//ajax页面的登陆判断
		if ($item == true) {
			if ($login_state == false) {
				exit();
			}
		} else {
			if ($login_state == false) {				
				$this->redirect($this->create_url('login/index'));
			}
		}
		
		return true;
	}
	
	/**
	 * 检测项目目录是否存在
	 */
	protected function parse_webapp_root() {
		
		//分析项目目录
		if (!is_dir(WEBAPP_ROOT)) {
			echo '对不起,项目(WebApp)根目录:', WEBAPP_ROOT, '不存在.请创建项目根目录';
			exit();
		}
		
		//分析应用目录
		if (!is_dir(WEBAPP_ROOT . 'application')) {
			echo '对不起!您还没有创建WebApp目录,请进行操作:WebApp管理->创建WebApp目录';
			exit();
		}
	}
}